import * as types from './types';
import { Toast, Modal } from 'antd-mobile';
import { push } from 'react-router-redux';
import 'whatwg-fetch';
import { getLocalUid, getLocalPassword, getLocalSchoolId, toastLoading, toastSuccess, toastFail, toastInfo, toastHide, myConfirm } from '../utils/func';
import { SERVER_HOST_API } from './server_info';

export function changeSelectedTab(v){
	return {
		type : types.CHANGE_SELECTED_TAB,
		v
	}
}

export function initSchoolList(){
	Toast.info('设备准备中');
	return function(dispatch){
		fetch(SERVER_HOST_API + '/index/waiting').then(function(res){
    		return res.json();
    	}).then(function(data){
    		Toast.hide();
    		toastLoading();
    		return fetch(SERVER_HOST_API + '/school/getList.json').then(function(res){
	    		return res.json();
	    	}).then(function(data){
	    		toastHide();
	    		if (data.status == 1){
	    			dispatch(setSchoolList(data.ext.schoolList))
	    		}else {
	    			//toastFail(data.msg, 1);
	    		}
	    	}).catch(function(e){
	    		toastHide();
	    		toastFail('服务器错误!', 1);
	    	});
    	});
    }
}
export function setSchoolList(schoolList){
	return {
		type : types.SET_SCHOOL_LIST,
		schoolList
	}
}
export function clearSchoolList(){
	return {
		type : types.CLEAR_SCHOOL_LIST
	}
}

export function login(username, password, school_id){
	return (dispatch, getState) => {
        let jsonData = {username:username, password:password, school_id:school_id};
        let body = 'jsonData=' + JSON.stringify(jsonData);

        toastLoading('正在提交...',  600);
		fetch(SERVER_HOST_API + '/teacher/login.json', {
			method:'POST', 
			headers: {
					    "Content-Type": "application/x-www-form-urlencoded" //指定了后请求的header就是Form data,而不是request payload
					  }, 
				body : body
		}).then(function(res){
			return res.json();
		}).then(function(data){
			toastHide();
			if (data.status == 1){
				localStorage.setItem("local_uid_teacher", data.ext.uid);
				localStorage.setItem("local_password_teacher", data.ext.password);
				localStorage.setItem("local_school_id", data.ext.school_id);
				toastSuccess(data.msg, 1);
				setTimeout(function(){dispatch(push('/'));}, 1500);
			}else {
				toastFail(data.msg, 1);
			}
		}).catch(function(e){
			toastHide();
			toastFail('服务器错误!', 1);
		});
    }
}

export function initInfo(){
	Toast.info('设备准备中');
	return function(dispatch){
		fetch(SERVER_HOST_API + '/index/waiting').then(function(res){
    		return res.json();
    	}).then(function(data){
    		Toast.hide(); //先销毁仅剩的一个Toast (即上面的Toast.info)
			toastLoading('正在初始化..'); 
	        return fetch(SERVER_HOST_API + '/teacher/getInfo.json?uid=' + getLocalUid() + '&password=' + getLocalPassword() + '&school_id=' + getLocalSchoolId()).then(function(res){
	    		return res.json();
	    	}).then(function(data){
	    		toastHide();
	    		if (data.status == 1){
	    			dispatch(setInfo(data.ext.info))
	    		}else {
	    			//toastFail(data.msg, 1);
	    		}
	    	}).catch(function(e){
	    		toastHide();
	    		toastFail('服务器错误!', 1);
	    	})
    	});
    }
}
export function setInfo(v){
	return {
		type : types.SET_INFO,
		v
	}
}
export function clearInfo(v){
	return {
		type : types.CLEAR_INFO,
		v
	}
}

export function checkout(localtion, scanContent){
	return (dispatch, getState) => {
        let jsonData = {uid:getLocalUid(), password:getLocalPassword(), school_id:getLocalSchoolId(), localtion:localtion, scanContent:scanContent}
        let body = 'jsonData=' + JSON.stringify(jsonData);
        toastLoading('正在提交...',  600);
		fetch(SERVER_HOST_API + '/teacher/checkout.json', {
			method:'POST', 
			headers: {
					    "Content-Type": "application/x-www-form-urlencoded" //指定了后请求的header就是Form data,而不是request payload
					  }, 
				body : body
		}).then(function(res){
			return res.json();
		}).then(function(data){
			toastHide();
			if (data.status == 1){
				dispatch(addCheckoutRecord(data.ext.checkoutInfo));
				Modal.alert('提示', data.msg + '，到课人数：' + data.ext.count, [
				    { text: '关闭', onPress: () => console.log('ok') },
				  ]);
			}else if (data.status == 2){
				Modal.alert('提示', data.msg, [
				    { text: '关闭', onPress: () => console.log('ok') },
				  ]);
			}else {
				toastFail(data.msg, 1);
			}
		}).catch(function(e){
			toastHide();
			toastFail('服务器错误', 1);
		});
    }
}
export function addCheckoutRecord(v){
	return {
		type : types.ADD_CHECKOUT_RECORD,
		v
	}
}

export function initCheckoutList(){
	return function(dispatch){
    	return fetch(SERVER_HOST_API + '/teacher/getCheckoutList.json?uid=' + getLocalUid() + '&password=' + getLocalPassword() + '&school_id=' + getLocalSchoolId()).then(function(res){
    		return res.json();
    	}).then(function(data){
    		if (data.status == 1){
    			dispatch(setCheckoutList(data.ext.checkoutList));	
    		}else {
    			//toastFail(data.msg, 1); //这里会打断前一个Toast的hide方法，使其不会关闭
    		}
    	}).catch(function(e){
    		console.log(e);
    	})
    }
}
export function setCheckoutList(v){
	return {
		type : types.SET_CHECKOUT_LIST,
		v
	}
}
export function getMoreCheckoutList(page){
	return function(dispatch){
		toastLoading('正在获取...',  600);
    	return fetch(SERVER_HOST_API + '/teacher/getCheckoutList.json?uid=' + getLocalUid() + '&password=' + getLocalPassword() + '&school_id=' + getLocalSchoolId() + '&p=' + page).then(function(res){
    		return res.json();
    	}).then(function(data){
    		toastHide();
    		if (data.status == 1){
    			dispatch(setMoreCheckoutList(data.ext.checkoutList));
    		}else {
    			toastInfo(data.msg, 1);
    		}
    	}).catch(function(e){
    		toastFail('服务器错误!', 1);
    	})
    }
}
export function setMoreCheckoutList(v){
	return {
		type : types.SET_MORE_CHECKOUT_LIST,
		v
	}
}

export function clearCheckoutList(){
	return {
		type : types.CLEAR_CHECKOUT_LIST
	}
}

export function getCheckoutDetail(checkout_id){ //实际上就是取得签退ID对应的签到列表 server:getCheckinList
	return function(dispatch){
		toastLoading('正在获取...',  600);
    	return fetch(SERVER_HOST_API + '/teacher/getCheckinList.json?uid=' + getLocalUid() + '&password=' + getLocalPassword() + '&school_id=' + getLocalSchoolId() + '&checkout_id=' + checkout_id).then(function(res){
    		return res.json();
    	}).then(function(data){
    		toastHide();
    		if (data.status == 1){
    			dispatch(setCheckoutDetail(checkout_id, data.ext.checkinList));
    		}else {
    			//toastInfo(data.msg, 1);
    		}
    	}).catch(function(e){
    		toastFail('服务器错误!', 1);
    	})
    }
}
export function setCheckoutDetail(checkout_id, v){
	return {
		type : types.SET_CHECKOUT_DETAIL,
		checkout_id,
		v
	}
}
export function clearAllCheckoutDetail(){
	return {
		type : types.CLEAR_ALL_CHECKOUT_DETAIL
	}
}

export function logout(){
	return (dispatch, getState) => {
		Modal.alert('退出', '确定退出吗?', [
		    { text: '取消', onPress: () => console.log('cancel') },
		    { text: '确定', onPress: () => {
		    	localStorage.removeItem("local_uid_teacher");
				localStorage.removeItem("local_password_teacher");
				localStorage.removeItem("local_school_id");

				//clear
				dispatch(clearInfo());
				dispatch(clearCheckoutList());
				dispatch(clearAllCheckoutDetail());

				setTimeout(function(){dispatch(push('/login'));}, 500);
		    } },
		  ]);
	}
}